/**
 *  Copyright 2011 Marco Berri - marcoberri@gmail.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 **/
package com.url;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.utils.DateTimeUtil;
import com.utils.Default;
import com.utils.HttpUtil;
import com.utils.IOUtil;
import com.utils.StringUtil;
import java.io.File;

/**
 *
 * @author Marco Berri marcoberri@gmail.com
 */
public class Save extends com.Base {

    /**
     * parametro url da cui partire
     */
    protected String url;
    /**
     * parametro tipologia di risultato
     */
    protected String type = "xml";
    /**
     * parametro valido fino
     */
    protected String best_before = "12M";
    /**
     * parametro idenfifiace se deve essere univoco
     */
    protected boolean unique = true;
    /**
     * conf charset di uscita
     */
    protected String charset = "UTF-8";
    /**
     * parametro che idenfica la possibilità di fare un url personalizzato
     */
    protected String personal;

    /** 
     * 
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        if (isIpNullOrSpam(request.getRemoteAddr())) {
            return;
        }

        //prelevo i parametri in arrivo che devono essere 1... per ora...
        String url_originale = url = request.getParameter("url");

        type = Default.toString(request.getParameter("type"), type).toLowerCase();

        unique = Default.toBoolean(request.getParameter("unique"), unique);

        best_before = Default.toString(request.getParameter("best_before"), DateTimeUtil.getNowWithOffsetAndFormat(this.conf.getUrl().getBest_before(), "yyyy-MM-dd HH:mm:ss"));

        if (StringUtil.isNullOrEmpty(url)) {
            fatal("url is empty");
            return;
        }

        charset = (StringUtil.isNullOrEmpty(this.conf.getUrl().getCharset()) ? this.charset : this.conf.getUrl().getCharset());


        //TO DO: sostituire tutte le tipologie di protoollo... da capire...
        url = url.replaceAll("http://", "");

        String id = null;

        String proxy = request.getContextPath();


        if (!StringUtil.isNullOrEmpty(conf.getProxy().getUrl())) {
            proxy = proxy.replaceAll(conf.getProxy().getUrl(), Default.toString(conf.getProxy().getTo(), "/"));
        }


        if (!StringUtil.isNullOrEmpty(conf.getProxy().getDomain())) {
            proxy = conf.getProxy().getDomain() + "/" + proxy;
        }


        boolean generate = false;

        try {


            Statement stat = this.conn_url.createStatement();


            //verifico che non sia già esistente nel db andando via di chiave md5
            String md5 = Default.md5(url);

            ResultSet rs;

            //se non deve essere univoco verifico se esiste
            if (!unique) {

                rs = stat.executeQuery("select id,url,md5 from url where md5='" + md5 + "'");

                //se esiste mi prendo l'id
                if (rs.next()) {
                    id = rs.getString("id");
                    rs.close();

                } else {
                    //se non esiste devo generalo
                    generate = true;
                }

            }

            //se deve essere univoco o deve essere generato
            if (unique || generate) {

                int let = 1;
                int check = 0;
                ResultSet rs2;

                do {

                    id = randomString(let);
                    rs2 = stat.executeQuery("select id,url from url where id='" + id + "'");
                    check++;

                    //incremento le lettere dopo 10 tentativi
                    if (check == 10) {
                        check = 0;
                        let++;
                    }
                } while (rs2.next());

                rs2.close();

                stat.executeUpdate("insert into url(id,url,md5,t_end) values('" + id + "','" + url + "','" + md5 + "','" + best_before + "')");
            }


            ///salvo in cache
            putUrlIdToMap(id, url);


            stat.close();

        } catch (SQLException e) {
            fatal("SQLException:" + e, e);
            return;
        }


        String short_url = IOUtil.normalizedPath(proxy + "/r/" + id);
        //da sistemare questa porcata....
        short_url = short_url.replaceAll("http:/", "http://");


        if (type.equals("xml")) {
            response.setContentType("text/xml;charset=" + this.charset);

        } else if (type.equals("html")) {
            response.setContentType("text/html;charset=" + this.charset);

        } else if (type.equals("json")) {
            response.setContentType("application/json;charset=" + this.charset);

        } else {
            response.sendError(response.SC_INTERNAL_SERVER_ERROR);
            return;
        }


        saveStatsSave(request, id);


        if (this.conf.getQrcode() != null && (unique || generate)) {
            File dest = new File(this.path_app_root + "/" + this.conf.getQrcode().getStorage() + "/");
            org.apache.commons.io.FileUtils.forceMkdir(dest);
            HttpUtil.downloadData(this.conf.getQrcode().getUrl() + "?cht=qr&chs=" + this.conf.getQrcode().getDim() + "&chl=" + short_url, dest.toString() + "/" + id + ".png");
        }

        PrintWriter out = response.getWriter();
        HashMap<String, Object> m = new HashMap<String, Object>();
        m.put("charset", this.charset);
        m.put("short", short_url);
        m.put("url", url_originale);
        m.put("new", (unique || generate));
        m.put("best_before", best_before);
        m.put("qrcode", short_url.replaceAll("\\/r\\/", "/q/"));

        out.println(velocity.render("template/" + type + ".vtl", m));
        out.close();


    }

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Save data and generate Short Url";
    }// </editor-fold>

    /**
     *
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

    }

    /**
     * Destroy
     */
    @Override
    public void destroy() {
        super.destroy();
    }
}
